// pages/editStudent/editStudent.js
var request = require('../../operation/operation.js')
var bxt = require('../../utils/bxt.js')
var userModel = require('../../models/user.js')
var edit = false; // 区分是编辑/新建学生模式
var canEditStudent = false; // 是否有权限编辑学生信息
var klassSid;  // 创建学生时使用，又上个界面传过来
var student;  // 绑定关系时使用，从getApp获取全局变量，值由上个界面保存进去
var relation = null;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    genders:[{'value':0,'name':'男生'},{'value':1,'name':'女生'}],
    genderIndex:0,
    relations: ['爸爸','妈妈','爷爷','奶奶','姥爷','姥姥'],
    relationIndex:0,
    disabled:false,
    student:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.studentSid) {
      edit = true;
      student = getApp().globalData.param
      relation = userModel.getRelationByStudentSid(student.sid)
      if (student.creatorSid == userModel.getCurrentUser().sid) {
        canEditStudent = true        
      }

      var relationIndex = 0
      if (relation) {
        relationIndex = this.getRelationIndex()
      }

      this.setData({
        student: student,
        genderIndex:student.gender.value,
        disabled: !canEditStudent,
        relationIndex: relationIndex,
        relation: relation
      })
    }else {
      canEditStudent = true
      klassSid = options.klassSid;
      wx.setNavigationBarTitle({
        title: '添加学生'
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    canEditStudent = false
    edit = false
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 切换性别事件处理函数 
   */
  bindGenderChange:function(event) {
    this.setData({
      genderIndex:event.detail.value
    })
  },

  /**
   * 切换关系事件处理函数
   */
  bindRelationChange:function(event) {
    this.setData({
      relationIndex: event.detail.value
    })
  },

  /**
   * 点击确定按钮事件处理函数
   */
  onNext:function(event) {
    if (canEditStudent && 0 == event.detail.value.name.length) {
      wx.showModal({
        title: '提示',
        content: '请输入完整姓名',
        showCancel:false
      })

      return
    }

    getApp().createFormId(event.detail.formId)

    if(true == canEditStudent) {
      this.editStudent(event.detail.value.name, event.detail.value.gender, this.data.relations[event.detail.value.relation])
    }else {
      this.editRelation(this.data.relations[event.detail.value.relation],student.sid)
    }    
  },

  /**
   * 编辑学生信息请求
   */
  editStudent:function(name,gender) {
    var that = this;
    var method = 'POST', path = '/students', params = {'name': name, 'gender': parseInt(gender) };
    if (true == edit) {
      method = 'PUT';
      path += '/' + student.sid;
    } else {
      params.klassSid = klassSid;
    }

    this.setButtonLoading(true)
    request.startRequest(method, path, params, true)
      .then(res => {
        that.setButtonLoading(false);
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          var student = data.object
          that.editRelation(that.data.relations[that.data.relationIndex], student.sid)
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      }).catch(e => {
        that.setButtonLoading(false);
        console.log(e)
        wx.showToast({
          title: '编辑学生失败',
          icon: 'none'
        })
      })
  },

  editRelation:function(relationName,studentId = '0') {
    var that = this;
    var method = 'POST', path = '/relations', params = { 'name': relationName};
    if (relation) {
      method = 'PUT';
      path += '/' + relation.sid;
    }else {
      params.studentSid	= studentId;
    }

    request.startRequest(method, path, params, true)
      .then(res => {
        that.setButtonLoading(false);
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          if (edit) {
            getApp().notificationCenter.post(bxt.BIND_ROLE_MESSAGE)
            getApp().autoBack('修改成功')
          }else {
            wx.navigateTo({
              url: '../studentFinished/studentFinished',
            })
          }
          
        } else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      }).catch(e => {
        that.setButtonLoading(false);
        wx.showToast({
          title: '编辑学生失败',
          icon: 'none'
        })
      })
  },

  /**
   * 设置按钮状态
   */
  setButtonLoading: function (loading) {
    this.setData({
      disabled: loading,
      loading: loading
    })
  },

  getRelationIndex:function() {
    var relatios = this.data.relations, size = relatios.length, index = 0;
    for(index = 0; index < size; index++) {
      if (relatios[index] == relation.name) {
        break;
      }
    }

    return index;
  }

})